package com.example.ssmxuankeback.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.support.SFunction;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.ssmxuankeback.common.RestBean;
import com.example.ssmxuankeback.dto.CourseDTO;
import com.example.ssmxuankeback.dto.CoursePageQueryDTO;
import com.example.ssmxuankeback.entity.Course;
import com.example.ssmxuankeback.interfaces.ICourseMapper;
import com.example.ssmxuankeback.mapper.CourseMapper;
import com.example.ssmxuankeback.service.CourseService;
import com.example.ssmxuankeback.vo.CourseVO;
import com.example.ssmxuankeback.vo.PageVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class CourseServiceImpl
        extends ServiceImpl<CourseMapper, Course>
        implements CourseService {

    @Autowired
    CourseMapper courseMapper;

    @Override
    public RestBean<CourseVO> addCourse(CourseDTO dto) {
        // 校验课程ID唯一性
        if (lambdaQuery().eq(Course::getCourseId, dto.getCourseId()).exists()) {
            return RestBean.failure(409, "课程ID已存在");
        }

        Course course = ICourseMapper.INSTANCT.dtoToEntity(dto);
        course.setCurrentSeats(0); // 初始化选课人数

        return save(course) ?
                RestBean.success(ICourseMapper.INSTANCT.entityToVO(course)) :
                RestBean.failure(500, "课程创建失败");
    }

    @Override
    public RestBean<CourseVO> getCourseByCourseId(Long id) {
        Course course = getById(id);
        if (course == null) {
            return RestBean.failure(404, "课程不存在");
        }
        return RestBean.success(ICourseMapper.INSTANCT.entityToVO(course));
    }

    @Override
    public RestBean<CourseVO> updateCourse(CourseDTO dto) {
        Course course = ICourseMapper.INSTANCT.dtoToEntity(dto);
        courseMapper.updateById(course);
        return RestBean.success(ICourseMapper.INSTANCT.entityToVO(course));
    }

    @Override
    public RestBean<CourseVO> deleteCourseById(Long id) {
        // 检查是否有选课记录
        return removeById(id) ?
                RestBean.success() :
                RestBean.failure(500, "删除失败");
    }

    @Override
    public RestBean<List<CourseVO>> getCourseByTeacherId(Long id) {
        List<Course> courses = lambdaQuery()
                .eq(Course::getTeacherId, id)
                .list();

        List<CourseVO> vos = courses.stream()
                .map(ICourseMapper.INSTANCT::entityToVO)
                .collect(Collectors.toList());

        return RestBean.success(vos);
    }

    @Override
    public RestBean<PageVO<CourseVO>> listByPage(CoursePageQueryDTO queryDTO) {
        // 1. 构建分页参数
        Page<Course> page = new Page<>(queryDTO.getPageNum(), queryDTO.getPageSize());

        // 2. 构建查询条件
        LambdaQueryWrapper<Course> queryWrapper = new LambdaQueryWrapper<>();
        // 模糊查询课程名称
        if (StringUtils.isNotBlank(queryDTO.getCourseName())) {
            queryWrapper.like(Course::getCourseName, queryDTO.getCourseName());
        }
        // 精确匹配教师ID
        if (queryDTO.getTeacherId() != null) {
            queryWrapper.eq(Course::getTeacherId, queryDTO.getTeacherId());
        }
        // 排序逻辑
        if (StringUtils.isNotBlank(queryDTO.getSortBy())) {
            String order = "asc".equalsIgnoreCase(queryDTO.getSortOrder()) ? "ASC" : "DESC";
            queryWrapper.orderBy(true, "asc".equalsIgnoreCase(order), getSortField(queryDTO.getSortBy()));
        }

        // 3. 执行分页查询
        IPage<Course> pageResult = courseMapper.selectPage(page, queryWrapper);

        // 4. 将 Entity 转换为 VO
        List<CourseVO> dtoList = pageResult.getRecords().stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());

        // 5. 返回分页结果
        return RestBean.success(PageVO.of(pageResult, dtoList));
    }

    private CourseVO convertToVO(Course course) {
        return ICourseMapper.INSTANCT.entityToVO(course);
    }
    // 安全获取排序字段（防止SQL注入）
    private SFunction<Course, ?> getSortField(String sortBy) {
        return switch (sortBy) {
            case "courseName" -> Course::getCourseName;
            case "credit" -> Course::getCredit;
            default -> Course::getCourseId; // 默认按ID排序
        };
    }
}